package com.yzkj.cpjxc.business.controller;

import com.yzkj.cpjxc.business.domain.Dickm;
import com.yzkj.cpjxc.business.domain.DickmQueryVo;
import com.yzkj.cpjxc.business.domain.DickmShowVo;
import com.yzkj.cpjxc.business.service.DickmService;
import com.yzkj.cpjxc.business.framework.common.BusinessMap;
import com.yzkj.cpjxc.business.framework.common.CSRFTokenManager;
import com.yzkj.cpjxc.business.framework.common.Constants;
import com.yzkj.cpjxc.business.framework.common.Pager;
import com.yzkj.cpjxc.business.framework.utils.CollectionHelp;
import com.yzkj.cpjxc.business.domain.ZTreeComm;
import com.yzkj.cpjxc.business.system.interceptor.DoLog;
import com.yzkj.cpjxc.business.system.interceptor.Permission;
import com.yzkj.cpjxc.business.domain.JieZhang;
import com.yzkj.cpjxc.business.domain.ZhangTao;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 科目类别控制器
 */
@Controller
@RequestMapping("/dickm")
public class DickmController extends BaseController {

	@Autowired
	private DickmService dickmService;

	@RequestMapping("/list")
	@DoLog(cnContent = "查看科目类别列表信息")
	@Permission(name = "dickm.view")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response, Dickm dickm) throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("dickm", dickm);
		modelMap.put("GET_KMFL_MAP", Constants.GET_KMFL_MAP);
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		return new ModelAndView("dictionary/dickm/mgr").addAllObjects(modelMap);
	}

	@RequestMapping("/mgr")
	@DoLog(cnContent = "加载权限管理树", value = false)
	@Permission(name = "dickm.view")
	public String mgr(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			List<ZTreeComm> ztreeList = new ArrayList<ZTreeComm>();

			List<DickmShowVo> list = dickmService.searchAllList(request.getParameter("leiBie"));
			if (CollectionHelp.isNotBank(list)) {
				ZTreeComm ztreeComm = null;
				for (DickmShowVo vo : list) {
					ztreeComm = new ZTreeComm();
					ztreeComm.setId(vo.getUuid());
					ztreeComm.setpId(vo.getParentUuid());
					ztreeComm.setName(vo.getDicCode() + " " + vo.getDicName());
					if (vo.getChileCount() > 0) {
						ztreeComm.setOpen(Constants.IS_TRUE);
					} else {
						ztreeComm.setOpen(Constants.IS_FALSE);
					}
					ztreeList.add(ztreeComm);
				}
			}
			// 转成json输出到浏览器展示
			return this.ajax(response, ztreeList);
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/ajaxPage")
	@DoLog(cnContent = "科目类别列表ajax分页")
	@Permission(name = "dickm.view")
	public String ajaxPage(HttpServletRequest request, HttpServletResponse response, Dickm dickm) throws Exception {
		try {
			Pager<DickmShowVo> p = new Pager<DickmShowVo>();
			boolean exportExcel = BooleanUtils.toBoolean(request.getParameter(EXPORT_EXCEL));
			if (exportExcel) {
				return null;
			} else {
				String currentPage = request.getParameter(Pager.MY_PAGINATION_CURRENT_PAGE);
				p.setCurrentPage(Integer.parseInt(currentPage == null ? "1" : currentPage));
				Pager<DickmShowVo> pager = dickmService.search(p, dickm);
				this.genPageJson(response, pager);
				return null;
			}
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/toAdd")
	@DoLog(cnContent = "去到添加科目类别页面")
	@Permission(name = "dickm.add")
	public ModelAndView toAdd(HttpServletRequest request, HttpServletResponse response, Dickm dickm) throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		modelMap.put("dicMap", dickmService.getDictionaryMap2());
		modelMap.put("GET_KMFL_MAP", Constants.GET_KMFL_MAP);

		String parentId = request.getParameter("parentId");
		if (StringUtils.isNotBlank(parentId)) {
			Dickm parentDickm = dickmService.getById(parentId);
			modelMap.put("parentDickm", parentDickm);
		}

		String currKeMuFenLei = request.getParameter("currKeMuFenLei");
		modelMap.put("currKeMuFenLei", currKeMuFenLei);

		return new ModelAndView("dictionary/dickm/add").addAllObjects(modelMap);
	}

	@RequestMapping("/add")
	@DoLog(cnContent = "添加科目类别")
	@Permission(name = "dickm.add")
	public String add(HttpServletRequest request, HttpServletResponse response, Dickm dickm) throws Exception {
		try {
			BusinessMap bm = dickmService.create(dickm);
			return this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/toEdit")
	@DoLog(cnContent = "去到编辑科目类别页面")
	@Permission(name = "dickm.edit")
	public ModelAndView toEdit(HttpServletRequest request, HttpServletResponse response, Dickm dickm) throws Exception {
		Dickm result = dickmService.getById(dickm.getUuid());
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		modelMap.put("dickm", result);
		modelMap.put("GET_KMFL_MAP", Constants.GET_KMFL_MAP);
		modelMap.put("dicMap", dickmService.getDictionaryMap2());
		return new ModelAndView("dictionary/dickm/edit").addAllObjects(modelMap);
	}

	@RequestMapping("/edit")
	@DoLog(cnContent = "编辑科目类别")
	@Permission(name = "dickm.edit")
	public String edit(HttpServletRequest request, HttpServletResponse response, Dickm dickm) throws Exception {
		try {
			Dickm yuanShiData = dickmService.getById(dickm.getUuid());

			BusinessMap bm = dickmService.edit(dickm);

			// 如果父级code被修改 则需要更新所有关系信息
			if (bm.getIsSucc() && !StringUtils.equals(yuanShiData.getParentDicCode(), dickm.getParentDicCode())) {
				Dickm temp = new Dickm();
				temp.setLevelDicId(yuanShiData.getLevelDicId());
				List<Dickm> dictionaryList = dickmService.getDictionaryList(temp);
				for (Dickm ids : dictionaryList) {
					dickmService.edit(ids);
				}
			}

			return this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/view")
	@DoLog(cnContent = "查看科目类别信息")
	@Permission(name = "dickm.view")
	public ModelAndView view(HttpServletRequest request, HttpServletResponse response, Dickm dickm) throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		Dickm result = dickmService.getById(dickm.getUuid());
		modelMap.put("GET_KMFL_MAP", Constants.GET_KMFL_MAP);
		modelMap.put("dickm", result);
		return new ModelAndView("dictionary/dickm/view").addAllObjects(modelMap);
	}

	@RequestMapping("/delete")
	@DoLog(cnContent = "删除科目类别信息")
	@Permission(name = "dickm.delete")
	public String delete(HttpServletRequest request, HttpServletResponse response, Dickm dickm) throws Exception {
		try {

			Dickm ind = dickmService.getById(dickm.getUuid());
			Dickm temp = new Dickm();
			temp.setLevelDicId(ind.getLevelDicId());
			List<Dickm> dictionaryList = dickmService.getDictionaryList(temp);
			if (CollectionHelp.isNotBank(dictionaryList)) {
				return this.ajax(response, "该科目类别编码下存在子下属编码，不能删除！");
			}

			boolean flag = dickmService.delete(dickm.getUuid());
			return this.ajax(response, flag ? Constants.SUCCESS : Constants.ERROR);
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/getChildTree")
	@DoLog(cnContent = "获取科目类别节点树")
	public void getChildTree(HttpServletRequest request, HttpServletResponse response, Dickm dickm) throws Exception {

		// 查询该类别下面的子区划
		List<Dickm> icList = dickmService.getByParentDicCode(dickm);
		List<ZTreeComm> ZTreeCommList = new ArrayList<ZTreeComm>();
		// 封装成树结果
		for (Dickm ic : icList) {
			ZTreeComm ZTreeComm = new ZTreeComm();
			ZTreeComm.setpId(ic.getParentDicCode());
			ZTreeComm.setId(ic.getDicCode());
			ZTreeComm.setName(ic.getDicName());

			if (dickmService.isHavaChilds(ic.getDicCode())) {
				ZTreeComm.setIsParent("true");
			} else {
				ZTreeComm.setIsParent("false");
			}

			ZTreeCommList.add(ZTreeComm);
		}
		this.ajax(response, ZTreeCommList);
	}

	@RequestMapping("/getDickmByLikeCodeOrName")
	@DoLog(cnContent = "查询获取科目类别")
	public void getDickmByLikeCodeOrName(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String dicCodeOrName = request.getParameter("dicCodeOrName");
		if (StringUtils.isNotBlank(dicCodeOrName)) {
			String[] strs = dicCodeOrName.split(" ");
			if (strs.length > 0) {
				dicCodeOrName = strs[0];
			}
		}

		List<Dickm> icList = dickmService.getDickmByLikeCodeOrName(dicCodeOrName);
		this.ajax(response, icList);
	}

	// 财务初始余额++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	@RequestMapping("/toSetChuShiYuE")
	@DoLog(cnContent = "去到设置财务初始余额页面")
	@Permission(name = "dickm.setChuShiYuEView")
	public ModelAndView toSetChuShiYuE(HttpServletRequest request, HttpServletResponse response, Dickm dickm)
			throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		modelMap.put("GET_KMFL_MAP", Constants.GET_KMFL_MAP);

		// 获取本账套启用日期
		ZhangTao zt = (ZhangTao) request.getSession().getAttribute(Constants.CURRENT_ZHANG_TAO);
		int month = zt.getQyMonth();

		// 当前账套账期
		JieZhang jz = (JieZhang) request.getSession().getAttribute(Constants.CURRENT_JIE_ZHANG);

		// 如果当前会计期间大于启用账套期间 则不能允许修改初始余额 必须反结账到初始账期才能修改
		if (jz.getJzYear() - zt.getQyYear() == 0 && jz.getJzMonth() - zt.getQyMonth() == 0) {
			modelMap.put("isEdit", "true");
		} else {
			modelMap.put("isEdit", "false");
		}

		if (month == 1) {
			return new ModelAndView("dictionary/dickm/setChuShiYuE").addAllObjects(modelMap);
		} else {
			return new ModelAndView("dictionary/dickm/setChuShiYuE2").addAllObjects(modelMap);
		}
	}

	@RequestMapping("/ajaxList")
	@DoLog(cnContent = "科目类别列表ajax")
	@Permission(name = "dickm.setChuShiYuEView")
	public String ajaxList(HttpServletRequest request, HttpServletResponse response, DickmQueryVo dickm)
			throws Exception {
		try {
			ZhangTao zt = (ZhangTao) request.getSession().getAttribute(Constants.CURRENT_ZHANG_TAO);
			dickm.setZhangTaoId(zt.getUuid());
			List<DickmShowVo> list = dickmService.searchList(dickm);
			DickmQueryVo temp = null;
			DickmShowVo oneVo = null;
			
			BigDecimal b1 = null;
			BigDecimal b2 = null;
			BigDecimal b3 = null;
			BigDecimal b4 = null;
			BigDecimal b5 = null;
			
			double nianChuValue;
			for (DickmShowVo vo : list) {
				if (vo.getChileCount() > 0) {
					temp = new DickmQueryVo();
					temp.setZhangTaoId(zt.getUuid());
					temp.setDicCode(vo.getDicCode());
					oneVo = dickmService.searchOne(temp);

					// 期初余额1 //分转元
					if ("1".equals(vo.getYueFx())) {
						
						b3 = new BigDecimal(oneVo.getQcyrJieZongJi().toString());
						b4 = new BigDecimal(oneVo.getQcyrDaiZongJi().toString());
						vo.setQiChuValue(b3.subtract(b4).doubleValue());
						
					} else if ("-1".equals(vo.getYueFx())) {
						
						b3 = new BigDecimal(oneVo.getQcyrDaiZongJi().toString());
						b4 = new BigDecimal(oneVo.getQcyrJieZongJi().toString());
						vo.setQiChuValue(b3.subtract(b4).doubleValue());
						
					}
					b1 = new BigDecimal(vo.getQiChuValue());
					b2 = new BigDecimal(100);
					vo.setQiChuValue(b1.divide(b2).doubleValue());

					// 本年累计借方2 //分转元
					b1 = new BigDecimal(oneVo.getBnljJfValue());
					b2 = new BigDecimal(100);
					vo.setBnljJfValue(b1.divide(b2).doubleValue());

					// 本年累计贷方3 //分转元
					b1 = new BigDecimal(oneVo.getBnljDfValue());
					b2 = new BigDecimal(100);
					vo.setBnljDfValue(b1.divide(b2).doubleValue());

					// 设置年初余额4 //已经是元计算
					if ("1".equals(vo.getYueFx())) {// 借
						
						b3 = new BigDecimal(vo.getQiChuValue().toString());
						b4 = new BigDecimal(vo.getBnljDfValue().toString());
						b5 = new BigDecimal(vo.getBnljJfValue().toString());
						
						nianChuValue = b3.add(b4).subtract(b5).doubleValue();
						
					} else {// 贷
						
						b3 = new BigDecimal(vo.getQiChuValue().toString());
						b4 = new BigDecimal(vo.getBnljJfValue().toString());
						b5 = new BigDecimal(vo.getBnljDfValue().toString());
						
						nianChuValue = b3.add(b4).subtract(b5).doubleValue();
						
					}
					vo.setNianChuValue(nianChuValue);

					// 实际损益发生额5 //分转元
					b1 = new BigDecimal(oneVo.getShiJiSunYiValue());
					b2 = new BigDecimal(100);
					vo.setShiJiSunYiValue(b1.divide(b2).doubleValue());

				} else {

					// 期初余额1 //分转元
					b1 = new BigDecimal(vo.getQiChuValue());
					b2 = new BigDecimal(100);
					vo.setQiChuValue(b1.divide(b2).doubleValue());

					// 本年累计借方2 //分转元
					b1 = new BigDecimal(vo.getBnljJfValue());
					b2 = new BigDecimal(100);
					vo.setBnljJfValue(b1.divide(b2).doubleValue());

					// 本年累计贷方3 //分转元
					b1 = new BigDecimal(vo.getBnljDfValue());
					b2 = new BigDecimal(100);
					vo.setBnljDfValue(b1.divide(b2).doubleValue());

					// 设置年初余额4 //已经是元计算
					if ("1".equals(vo.getYueFx())) {// 借
						b3 = new BigDecimal(vo.getQiChuValue().toString());
						b4 = new BigDecimal(vo.getBnljDfValue().toString());
						b5 = new BigDecimal(vo.getBnljJfValue().toString());
						nianChuValue = b3.add(b4).subtract(b5).doubleValue();
						
					} else {// 贷
						
						b3 = new BigDecimal(vo.getQiChuValue().toString());
						b4 = new BigDecimal(vo.getBnljJfValue().toString());
						b5 = new BigDecimal(vo.getBnljDfValue().toString());
						nianChuValue = b3.add(b4).subtract(b5).doubleValue();
					}
					vo.setNianChuValue(nianChuValue);

					// 实际损益发生额5 //分转元
					b1 = new BigDecimal(vo.getShiJiSunYiValue());
					b2 = new BigDecimal(100);
					vo.setShiJiSunYiValue(b1.divide(b2).doubleValue());
				}
				
				// 期初余额1
				if(vo.getQiChuValue()==0) {
					vo.setQiChuValue(null);
				}

				// 本年累计借方2
				if(vo.getBnljJfValue()==0) {
					vo.setBnljJfValue(null);
				}

				// 本年累计贷方3
				if(vo.getBnljDfValue()==0) {
					vo.setBnljDfValue(null);
				}

				// 设置年初余额4
				if(vo.getNianChuValue()==0) {
					vo.setNianChuValue(null);
				}

				// 实际损益发生额5
				if(vo.getShiJiSunYiValue()==0) {
					vo.setShiJiSunYiValue(null);
				}
			}
			this.ajax(response, list);
			return null;
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/setChuShiYuE")
	@DoLog(cnContent = "设置财务初始余额")
	@Permission(name = "dickm.setChuShiYuE")
	public String setChuShiYuE(HttpServletRequest request, HttpServletResponse response, Dickm dickm) throws Exception {
		try {
			ZhangTao zt = (ZhangTao) request.getSession().getAttribute(Constants.CURRENT_ZHANG_TAO);

			String currKeMuFenLei = request.getParameter("currKeMuFenLei");
			String dataArray = request.getParameter("dataArray");

			List<DickmShowVo> pareList = new ArrayList<DickmShowVo>();

			if (StringUtils.isNotBlank(dataArray)) {
				String[] chlids = dataArray.split(",");
				String[] lbs = null;
				DickmShowVo vo = null;
				Dickm kmObj = null;
				for (String chlid : chlids) {
					if (StringUtils.isNotBlank(chlid)) {
						lbs = chlid.split("=");
						vo = new DickmShowVo();
						vo.setZhangTaoId(zt.getUuid());
						vo.setKeMuId(lbs[0]);
						vo.setQiChuValue(Double.parseDouble(lbs[1]) * 100);

						// 其他项默认设置为0
						vo.setBnljJfValue(0.0);
						vo.setBnljDfValue(0.0);
						vo.setShiJiSunYiValue(0.0);
						vo.setNianChuValue(0.0);

						vo.setLeiBie(currKeMuFenLei);
						kmObj = dickmService.getById(vo.getKeMuId());
						vo.setKmdm(kmObj.getDicCode());
						pareList.add(vo);
					}
				}
			}

			BusinessMap bm = dickmService.setChuShiYuE(zt, currKeMuFenLei, pareList);

			return this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());

		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/setChuShiYuE2")
	@DoLog(cnContent = "设置财务初始余额2")
	@Permission(name = "dickm.setChuShiYuE")
	public String setChuShiYuE2(HttpServletRequest request, HttpServletResponse response, Dickm dickm)
			throws Exception {
		try {
			ZhangTao zt = (ZhangTao) request.getSession().getAttribute(Constants.CURRENT_ZHANG_TAO);

			String currKeMuFenLei = request.getParameter("currKeMuFenLei");
			String dataArray = request.getParameter("dataArray");

			List<DickmShowVo> pareList = new ArrayList<DickmShowVo>();

			if (StringUtils.isNotBlank(dataArray)) {
				String[] chlids = dataArray.split(",");
				String[] lbs = null;
				String[] values = null;
				DickmShowVo vo = null;
				Dickm kmObj = null;
				double nianChuValue;
				
				BigDecimal b3 = null;
				BigDecimal b4 = null;
				BigDecimal b5 = null;
				
				for (String chlid : chlids) {
					if (StringUtils.isNotBlank(chlid)) {
						lbs = chlid.split("=");
						vo = new DickmShowVo();
						vo.setZhangTaoId(zt.getUuid());
						vo.setKeMuId(lbs[0]);

						values = lbs[1].split("_");

						// 元转分*100
						vo.setQiChuValue(Double.parseDouble(values[0]) * 100);
						vo.setBnljJfValue(Double.parseDouble(values[1]) * 100);
						vo.setBnljDfValue(Double.parseDouble(values[2]) * 100);
						vo.setShiJiSunYiValue(Double.parseDouble(values[3]) * 100);

						kmObj = dickmService.getById(vo.getKeMuId());
						// 设置年初余额
						if ("1".equals(kmObj.getYueFx())) {// 借
							
							b3 = new BigDecimal(vo.getQiChuValue().toString());
							b4 = new BigDecimal(vo.getBnljDfValue().toString());
							b5 = new BigDecimal(vo.getBnljJfValue().toString());
							nianChuValue = b3.add(b4).subtract(b5).doubleValue();
							
						} else {// 贷
							
							b3 = new BigDecimal(vo.getQiChuValue().toString());
							b4 = new BigDecimal(vo.getBnljJfValue().toString());
							b5 = new BigDecimal(vo.getBnljDfValue().toString());
							nianChuValue = b3.add(b4).subtract(b5).doubleValue();
							
						}
						// 已经是分之间的运算 所以不需要*100
						vo.setNianChuValue(nianChuValue);

						vo.setLeiBie(currKeMuFenLei);
						vo.setKmdm(kmObj.getDicCode());
						pareList.add(vo);
					}
				}
			}

			BusinessMap bm = dickmService.setChuShiYuE2(zt, currKeMuFenLei, pareList);
			return this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());

		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/ajaxTreeList")
	@DoLog(cnContent = "报表公式添加获取科目zTree类别列表ajax")
	public void ajaxTreeList(HttpServletRequest request, HttpServletResponse response, DickmQueryVo dickm)
			throws Exception {
		List<DickmShowVo> icList = dickmService.ajaxTreeList(dickm);
		List<ZTreeComm> ZTreeCommList = new ArrayList<ZTreeComm>();
		// 封装成树结果
		for (Dickm ic : icList) {
			ZTreeComm ZTreeComm = new ZTreeComm();
			ZTreeComm.setpId(ic.getParentDicCode());
			ZTreeComm.setId(ic.getDicCode());
			ZTreeComm.setName(ic.getDicCode() + " " + ic.getDicName());

			if (dickmService.isHavaChilds(ic.getDicCode())) {
				ZTreeComm.setIsParent("true");
			} else {
				ZTreeComm.setIsParent("false");
			}

			ZTreeCommList.add(ZTreeComm);
		}
		this.ajax(response, ZTreeCommList);
	}

}
